﻿<%@ WebHandler Language="C#" Class="Download" %>

using System.Web;
using System.Linq;
using System.IO;
using System.Diagnostics;

using ORM;
using Concret;

/// <summary>
/// </summary>
public class Download : HandlerBase
{
	public void dir(Dir dir, string range = null)
	{
		var (server, response) = (HttpContext.Current.Server, HttpContext.Current.Response);

		if (dir == null) throw new Error("参数错误，请刷新页面后重试") { Plain = true };

		var photos = string.IsNullOrEmpty(range) ? dir.Dir__Photo() : DbOp.Photo.GetByParameter((Photo.FIELD_ID, "in", range.Split(',')));
		if (photos.Count() > 200) throw new Error("最多一次性下载200张图片，请重新指定范围") { Plain = true };

		var files = photos.Select(photo => server.MapPath(photo.Path_Val));

		var ext = Helper.NewId.ToString("x") + ".zip";
		var zip = $"{dir.Title_Val.Replace(":", "：").Replace("/", "").Replace("\\", "").Replace("?", "").Replace("*", "").Replace("<", "").Replace(">", "").Replace("|", "")}.{ext}";

		var pi = new ProcessStartInfo { UseShellExecute = false, CreateNoWindow = false, FileName = server.MapPath("/7z/7z.exe") };
		for (var i = 0; i < files.Count(); i += 10)
		{
			pi.Arguments = $"a {server.MapPath("/7z/" + zip)} {files.JoinBy(" ")}";
			Process.Start(pi).WaitForExit();
		}

		response.ContentType = "APPLICATION/OCTET-STREAM";
		response.Headers["Content-Disposition"] = $@"attachment;filename=""{zip.Replace(ext, "zip")}""";
		response.TransmitFile(server.MapPath("/7z/" + zip));
		response.Flush();

		try { File.Delete(server.MapPath("/7z/" + zip)); } catch { }
	}

	public void photo(Photo photo)
	{
		if (photo == null) throw new Error("参数错误，请刷新页面后重试");
		var file = HttpContext.Current.Server.MapPath(photo.Path_Val);
		var response = HttpContext.Current.Response;
		response.ContentType = "APPLICATION/OCTET-STREAM";
		response.Headers["Content-Disposition"] = $@"attachment;filename=""{photo.Title_Val}""";
		response.TransmitFile(file);
	}
}